<!-- 分账子订单明细列表 -->
<template>
  <div>
    <a-modal :width="1300" title="分账子订单明细列表" :open="openForm" @cancel="onClose" :maskClosable="false" :destroyOnClose="true" :footer="false">
      <div>
        <a-form class="smart-query-form">
          <a-row class="smart-query-form-row">
            <a-col :span="7">
              <a-form-item label="分账订单号" class="smart-query-form-item">
                <a-input v-model:value="queryForm.id" placeholder="分账订单号" />
              </a-form-item>
            </a-col>
            <!-- <a-col :span="6">
              <a-form-item label="分账日期" class="smart-query-form-item">
                <a-range-picker class="w-full" v-model:value="queryForm.cTime" :valueFormat="'YYYY-MM-DD'" @change="onChangeTTime" />
              </a-form-item>
            </a-col> -->
            <a-col :span="6">
              <a-form-item label="退款状态" class="smart-query-form-item">
                <a-select v-model:value="queryForm.status" allowClear :options="ALLOC_DETAIL_STATUS" placeholder="请选择退款状态" />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item class="smart-query-form-item">
                <a-button type="primary" @click="getSettlementList">
                  <template #icon>
                    <SearchOutlined />
                  </template>
                  查询
                </a-button>
                <a-button @click="resetQuery" class="smart-margin-left10">
                  <template #icon>
                    <ReloadOutlined />
                  </template>
                  重置
                </a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>

        <!---------- 表格操作行 begin ----------->
        <a-row class="smart-table-btn-block" v-if="USER_TYPE == '4'">
          <div class="smart-table-title"></div>
          <div class="smart-table-setting-block">
            <a-button type="primary" class="m-r-3" @click="again"> 再次分账</a-button>
            <a-button type="primary" @click="finish"> 分账完结</a-button>
          </div>
        </a-row>
        <a-table
          v-if="tableData && tableData.length"
          :dataSource="tableData"
          :columns="columns"
          bordered
          childrenColumnName="allocDetails"
          :defaultExpandAllRows="true"
          :pagination="false"
          size="small"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <div class="smart-table-operate">
                <a-button @click="viewList(record)" type="link" v-if="record.id">退款明细</a-button>
              </div>
            </template>
          </template>
        </a-table>
      </div>
      <RefundList v-model:open="refundListOption.open" :row-data="refundListOption.rowData" />
    </a-modal>
  </div>
</template>
<script setup>
  import { computed, createVNode, ref, watch } from 'vue'
  import { SmartLoading } from '/src/components/framework/smart-loading'
  import { allocOrderApi as allocOrderApiOperation } from '/@/api/business/b-operation/alloc/alloc-order.js'
  import { allocOrderApi as allocOrderApiAgent } from '/@/api/business/b-agent/alloc/alloc-order.js'
  import { allocOrderApi as allocOrderApiMerchant } from '/@/api/business/b-merchant/alloc/alloc-order.js'
  import dayjs from 'dayjs'
  import { ALLOC_DETAIL_STATUS, RECEICER_TYPE } from '/@/constants/dict'
  import { formatToMoney, selectDictLabel } from '/@/utils/common'
  import { Modal } from 'ant-design-vue'
  import RefundList from './refund-list.vue'

  import { useUserStore } from '/@/store/modules/system/user'
  import { smartSentry } from '/@/lib/smart-sentry.js'
  import { ExclamationCircleOutlined } from '@ant-design/icons-vue'

  const USER_TYPE = useUserStore().userType // 用户类型: 1-平台;2-代理;4-商户

  const apiSource = {
    listApi: (data) => {
      if (USER_TYPE == '1') return allocOrderApiOperation.page(data)
      if (USER_TYPE == '2') return allocOrderApiAgent.page(data)
      if (USER_TYPE == '4') return allocOrderApiMerchant.page(data)
    },
    again: (data) => {
      if (USER_TYPE == '4') return allocOrderApiMerchant.again(data)
    },
    finish: (data) => {
      if (USER_TYPE == '4') return allocOrderApiMerchant.finish(data)
    },
  }

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {},
    },
  })
  // ------------------------ 事件 ------------------------

  const emit = defineEmits(['update:open', 'ok', 'cancel'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  // ------------------------ 显示与隐藏 ------------------------
  const queryFormState = {
    // cTime: [dayjs().startOf('day'), dayjs().endOf('day')], //交易时间
    // cTimeBegin: dayjs().startOf('day').valueOf(), //交易时间 开始
    // cTimeEnd: dayjs().endOf('day').valueOf(), //交易时间 结束
    id: undefined,
    status: undefined,
    pageNo: 1,
    pageSize: 100,
  }
  // 查询表单form
  const queryForm = ref({ ...queryFormState })

  async function getSettlementList(data) {
    tableLoading.value = true
    try {
      const payload = { ...queryForm.value, orderId: props.rowData?.id }
      delete payload.tTime
      let queryResult = await apiSource.listApi(payload)
      tableData.value = queryResult.data
      total.value = queryResult.total
    } catch (e) {
      smartSentry.captureError(e)
    } finally {
      tableLoading.value = false
    }
  }

  async function show(rowData) {
    console.log(rowData)

    queryForm.value.orderId = rowData.id
    await getSettlementList()
    // nextTick(() => {
    //   formRef.value?.clearValidate()
    // })
  }

  function onClose() {
    tableData.value = []
    // Object.assign(form, formDefault)
    emit('cancel', false)
    openForm.value = false
  }

  // 重置查询条件
  function resetQuery() {
    let pageSize = queryForm.value.pageSize
    Object.assign(queryForm.value, queryFormState)
    queryForm.value.pageSize = pageSize
    getSettlementList()
  }

  // 表格加载loading
  const tableLoading = ref(false)
  // 表格数据
  const tableData = ref([])
  // 总数
  const total = ref(0)
  // ------------------------ 表单 ------------------------

  /* 列表数据 */

  const columns = ref([
    // {
    //   title: '序号',
    //   dataIndex: 'index',
    //   customRender: ({ index }) => {
    //     return (queryForm.value.pageNo - 1) * queryForm.value.pageSize + index + 1
    //   },
    // },
    {
      title: '分账订单号',
      dataIndex: 'id',
      width: 180,
      ellipsis: true,
    },
    {
      title: '分账时间',
      dataIndex: 'cTime',
      customRender: (column) => (column.text ? dayjs(column.text).format('YYYY-MM-DD HH:mm:ss') : ''),
      width: 180,
      ellipsis: true,
    },
    {
      title: '商家账户/商户号',
      dataIndex: 'channelMchid',
      customRender: (column) => (column.text ? column.text : ''),
      ellipsis: true,
    },
    {
      title: '分账接收方',
      dataIndex: 'receiverAccount',
      customRender: (column) => (column.text ? column.text : ''),
      ellipsis: true,
    },
    {
      title: '接收方账户类型',
      dataIndex: 'receiverType',
      customRender: ({ text }) => {
        return text != null && text !== '' ? selectDictLabel(RECEICER_TYPE, text) : ''
      },
      ellipsis: true,
    },
    {
      title: '接收方姓名',
      dataIndex: 'receiverName',
      customRender: (column) => (column.text ? column.text : ''),
      ellipsis: true,
    },
    {
      title: '分账金额',
      dataIndex: 'amount',
      customRender: (column) => (column.text ? formatToMoney(column.text / 100) : ''),
      ellipsis: true,
    },
    {
      title: '退款金额',
      dataIndex: 'refundAmount',
      customRender: (column) => (column.text ? formatToMoney(column.text / 100) : ''),
      ellipsis: true,
    },
    {
      title: '分账状态',
      dataIndex: 'status',
      customRender: ({ text }) => {
        return selectDictLabel(ALLOC_DETAIL_STATUS, text)
      },
      ellipsis: true,
    },
    {
      title: '分账失败原因',
      dataIndex: 'errorMsg',
      customRender: (column) => (column.text ? column.text : ''),
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 80,
    },
  ])

  // 时间选择
  function onChangeTTime(dates) {
    queryForm.value.cTimeBegin = dates[0].valueOf()
    queryForm.value.cTimeEnd = dates[1].valueOf()
  }

  // 查看退款明细
  const refundListOption = ref({
    open: false,
    rowData: {},
  })
  const viewList = (row) => {
    refundListOption.value = {
      open: true,
      rowData: row,
    }
  }

  // 分账
  function again() {
    Modal.confirm({
      title: '分账',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要再次分账吗?',
      okText: '分账',
      okType: 'danger',
      async onOk() {
        SmartLoading.show()
        try {
          await apiSource.again({ orderId: props.rowData?.id })
          await getSettlementList()
        } catch (error) {
          smartSentry.captureError(error)
        } finally {
          SmartLoading.hide()
        }
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  // 分账
  function finish() {
    Modal.confirm({
      title: '完结',
      icon: createVNode(ExclamationCircleOutlined),
      content: '确定要完结分账吗?',
      okText: '完结',
      okType: 'danger',
      async onOk() {
        SmartLoading.show()
        try {
          await apiSource.finish({ orderId: props.rowData?.id })
          await getSettlementList()
        } catch (error) {
          smartSentry.captureError(error)
        } finally {
          SmartLoading.hide()
        }
      },
      cancelText: '取消',
      onCancel() {},
    })
  }

  /* 列表数据 */

  defineExpose({
    show,
  })
  // 切换订单号选择
  watch(
    () => queryForm.value.orderField,
    (val, oldVal) => {
      if (val) {
        queryForm.value[oldVal] = undefined
      }
    },
  )
  watch(
    [() => props.rowData, () => props.open],
    (val) => {
      if (props.open && props.rowData) {
        show(val[0])
      }
    },
    { immediate: true },
  )
</script>
